package config

import (
	"context"
	"database/sql"
	"log"
	"sync"

	"entgo.io/ent/dialect"
	entsql "entgo.io/ent/dialect/sql"
	_ "github.com/jackc/pgx/v5/stdlib"

	"shaw.com/entPj/ent"
)

const Port string = ":8080"

var (
	dbClient *ent.Client
	once     sync.Once
)

func GetDbinstance() *ent.Client {
	// sync.Once保证初始化代码只执行一次，即使在多goroutine环境下也是安全的。
	once.Do(func() {
		db, err := sql.Open("pgx", "postgresql://postgres:XZq241476@101.200.129.169:5432/pjdatabase")
		if err != nil {
			log.Fatal(err)
		}

		drv := entsql.OpenDB(dialect.Postgres, db)
		client := ent.NewClient(ent.Driver(drv))

		if err := client.Schema.Create(context.Background()); err != nil {
			log.Fatalf("failed creating schema resources: %v", err)
		}

		dbClient = client
	})
	return dbClient
}
